#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include "queue.h"


sem_t semr,semw;
struct queue *que;
pthread_mutex_t  mutex;

int run_flag = 1;


void *fun1(void *arg)
{
	int dat = 0;

	while(run_flag == 1)
	{
		printf("please input data:\n");
		//scanf("%d",&dat);
		dat = dat + 1;


		sem_wait(&semw);
		if(run_flag == 0) break;
		pthread_mutex_lock(&mutex);
		push(dat,que);
		sem_post(&semr);
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}

		printf("1:%d\n",__LINE__);

}

void *fun2(void *arg)
{
	int dat = 0;
	while(run_flag == 1)
	{

		sem_wait(&semr);
		if(run_flag == 0) break;
		pthread_mutex_lock(&mutex);
		dat = front(que);
		pop(que);
		sem_post(&semw);

		pthread_mutex_unlock(&mutex);

	    //sleep(1);

		dat = dat + 2;
		printf("%d\n",dat);
		
	}

		printf("2:%d\n",__LINE__);

}


int main()
{

	pthread_t tid1 = 0;
	int ret = 0;
	pthread_t tids[10] = {0};


	sem_init(&semw,0,100);
	sem_init(&semr,0,0);
	que = create_queue();
	pthread_mutex_init(&mutex,NULL);

	ret = pthread_create(&tid1,NULL,fun1,NULL);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}

  for(int i = 0;i < 10;i++)
  {
	ret = pthread_create(&tids[i],NULL,fun2,NULL);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}
  }

	int sel = 0;
	while(run_flag == 1)
	{
		printf("1--status,2--exit\n");
		printf("please input your choice\n");
		scanf("%d",&sel);
		if(sel == 2)
		{
			run_flag = 0;
			break;
		}else if(sel == 1)
		{
			printf("size of queue is %d\n",size(que));
		}
	}



	sem_post(&semw);

	for(int i = 0;i < 10;i++)
	{
		sem_post(&semr);
	}

	
	pthread_join(tid1,NULL);
	
	for(int i = 0;i < 10;i++)
	{
		pthread_join(tids[i],NULL);
	}

	sem_destroy(&semr);
	sem_destroy(&semw);
	pthread_mutex_destroy(&mutex);



	return 0;

}





